<template>
  <div id="main">
    <!-- 面包屑导航 -->
    <!-- <el-breadcrumb separator-class="el-icon-arrow-right" class="margin-t10">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>Google认证</el-breadcrumb-item>
    </el-breadcrumb> -->
    <div class="box-card  boxBlock" style="margin-top: 0;">
      <div  class="dialogItem" > 
        <span>Google认证</span> 
      </div>
      <el-form
        class="padding-r35"
        label-width="100px"
        label-position="right"
        :model="gAForm"
        ref="gAForm"
        :rules="gAFormRules"
        v-if="!userInfo.google"
      >

        <template >
          <el-form-item label="秘钥绑定:" prop="secret">
            <el-input v-model="gAForm.secret" disabled ></el-input>
          </el-form-item>
          <el-form-item label="扫码绑定:" prop="secret">
            <img :src="qrCodeSrc" alt="QR Code" />
          </el-form-item> 
          <el-form-item  v-if="setep==1">
            <el-button type="primary"  
              @click="verArry.includes('/api/googleAuth/generateGoogleSecret')?getSecretShow():getSecret()"  
              :disabled="disabled">
                获取秘钥
              </el-button>
          </el-form-item>           
        </template>
        <template v-if="setep==2">
          <el-form-item label="验证码:" prop="code">
            <el-input v-model="gAForm.code"></el-input>
          </el-form-item> 
  
          <el-form-item class="wid-8 aline-c">
            <el-button type="primary"  
            @click="verArry.includes('/api/googleAuth/bindGoogle')?verShow():refer()" 

            :disabled="disabled">
              绑定Google
            </el-button>
            <!-- <el-button type="success" disabled v-if="userInfo.google">
              Google已绑定
            </el-button> -->
          </el-form-item>
        </template> 
        
      </el-form>
      <div v-else class="aline-c">
        <img src="~@/assets/img/goolA.png" alt="" />
        <h2>Google已绑定</h2>
      </div>
    </div>
    <codeChoose ref="codeRef" :fromType="verType"  @setParam="setData"></codeChoose>
  </div>
</template>
<script>
import { mapState, mapGetters } from "vuex";
import codeChoose from '@/components/codeChoose.vue'
import {
  setStoreS,
  getStoreS,
  removeStoreS,
  insertCharacter,
} from "../../utils/util";
import {
  baseURL,
  req,
  reqJson,
  encrypt,
  decrypt,
  reqtoken,
  service,
  getUrl,
} from "../../api/axiosFun";
import QRCode from "qrcode";

export default {
  data() {
    return {
      disabled: false,
      qrCodeSrc: "",
      gAForm: {
        secret: "",
        code: "",
      },
      gAFormRules: {
        code: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          {
            pattern: /^\d{6}$/,
            message: "请输入正确的验证码",
            trigger: "blur",
          },
        ],
      },
      userInfo: "",
      verArry:[],
      verType:'',
      setep:1
    };
  },
  created() {
    // if (this.$store.state.user) {
    //   this.userInfo = JSON.parse(this.$store.state.user);
    // } else {
    this.getuserInfo();
    // }
    // this.getSecret();
  },
   // 注册组件
   components: { 
    codeChoose
  }, 
  computed: {
    ...mapGetters(["getUser"]),
  },
  watch: {
    getUser(newVal) {
      this.userInfo = JSON.parse(newVal);
    },
  },
  methods: {
    verShow(){
      this.$refs.gAForm.validate((valid) => {
          if (valid) {
            this.$refs.codeRef.openDialog();  
          }
      })
       
    },
    setData(val,type) {  
      if(type=='get'){
        this.getSecret(val)
      }else{
        this.refer(val);
      }
      
    },
    getSecretShow(){
      this.verType = 'get'
      this.$refs.codeRef.openDialog();  
    },
 
    getSecret(val) { 
        reqJson('get',"/api/googleAuth/generateGoogleSecret",{ },{
            headers:{
              ...val
            }
          })  
      // service
      //   .get("/api/googleAuth/generateGoogleSecret", {})
        .then((res) => { 
          if (res.code == 0) {
            this.gAForm.secret = res.data.secret;
            this.generateQRCode(res.data.secretQrCode);
            this.setep = 2;
          } else {
            this.$message({
              type: "info",
              message: res.msg,
            });
          }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    generateQRCode(text) {
      QRCode.toDataURL(text, { errorCorrectionLevel: "H" })
        .then((url) => {
          this.qrCodeSrc = url;
        })
        .catch((err) => {
          console.error(err);
        });
    },
    refer(val) { 
      this.$refs.gAForm.validate((valid) => {
        if (valid) {
          this.disabled = true;
          let url = getUrl(this.gAForm); 
          reqJson('post',"/api/googleAuth/bindGoogle" + url,{ },{
            headers:{
              ...val
            }
          })  
          // service
          //   .post("/api/googleAuth/bindGoogle" + url, {})
            .then((res) => { 
              this.disabled = false;
              if (res.code == 0) {
                this.getuserInfo();
                this.$message.success("绑定成功！");
              } else {
                this.$message.error(res.msg);
                return;
              }
            })
            .catch((err) => {
              this.$message.error(err);
            });
        } else {
          this.disabled = false;
          return false;
        }
      });
    },
    getuserInfo() {
      service
        .get("/api/photon/getUserInfo", {})
        .then((res) => { 
          if (res.code == 0) {
            this.userInfo = res.data;
            this.$store.commit("user", JSON.stringify(res.data));
            if(this.userInfo&&this.userInfo.verifyApi){
            this.verArry =  this.userInfo.verifyApi.split(',');
          } 
          } else {
            this.$message({
              type: "info",
              message: res.msg,
            });
          }
        })
        .catch((err) => {});
    },
  },
};
</script>

<style scoped>
.box-card .el-form {
  width: 40%; 
  text-align: left;
  padding: 40px 0;
}
</style>
